package com.fsnbigdata.web;
import com.fsnbigdata.domain.Vegetation;
import com.fsnbigdata.enums.ResultEnum;
import com.fsnbigdata.exception.ParamException;
import com.fsnbigdata.util.ReflectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.roo.addon.web.mvc.controller.annotations.ControllerType;
import org.springframework.roo.addon.web.mvc.controller.annotations.RooController;
import org.springframework.roo.addon.web.mvc.controller.annotations.responses.json.RooJSON;
import com.fsnbigdata.service.api.VegetationService;
import io.springlets.web.NotFoundException;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.util.UriComponents;
import springfox.documentation.annotations.ApiIgnore;

import java.lang.reflect.Method;

/**
 * = VegetationsItemJsonController
 *
 * TODO Auto-generated class documentation
 *
 */
@RooController(entity = Vegetation.class, pathPrefix = "/api", type = ControllerType.ITEM)
@RooJSON
@RestController
@RequestMapping(value = "/api/vegetations/{id}", name = "VegetationsItemJsonController", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = "Vegetation", description = "植被" )
public class VegetationsItemJsonController {

    /**
     * TODO Auto-generated attribute documentation
     *
     */
    private VegetationService vegetationService;

    /**
     * TODO Auto-generated constructor documentation
     *
     * @param vegetationService
     */
    @Autowired
    public VegetationsItemJsonController(VegetationService vegetationService) {
        this.vegetationService = vegetationService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @return VegetationService
     */
    public VegetationService getVegetationService() {
        return vegetationService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param vegetationService
     */
    public void setVegetationService(VegetationService vegetationService) {
        this.vegetationService = vegetationService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param id
     * @return Vegetation
     */
    @ModelAttribute
    public Vegetation getVegetation(@PathVariable("id") Long id) {
        Vegetation vegetation = vegetationService.findOne(id);
        if (vegetation == null) {
            throw new NotFoundException(String.format("Vegetation with identifier '%s' not found", id));
        }
        return vegetation;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param vegetation
     * @return ResponseEntity
     */
    @GetMapping(name = "show")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "path", dataType = "int", required = true)
    })
    //@PreAuthorize("hasRole('USER')")
    public ResponseEntity<?> show(@ApiIgnore @ModelAttribute Vegetation vegetation) {
        return ResponseEntity.ok(vegetation);
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param vegetation
     * @return UriComponents
     */
    public static UriComponents showURI(Vegetation vegetation) {
        return MvcUriComponentsBuilder.fromMethodCall(MvcUriComponentsBuilder.on(VegetationsItemJsonController.class).show(vegetation)).buildAndExpand(vegetation.getId()).encode();
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param storedVegetation
     * @param vegetation
     * @param result
     * @return ResponseEntity
     */
    @PutMapping(name = "update")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "path", dataType = "int", required = true)
    })
    @PreAuthorize("hasRole('DB_VEGETATION')")
    @ApiOperation(value = "",notes = "update")
    public ResponseEntity<?> update(@ApiIgnore @ModelAttribute Vegetation storedVegetation, @Valid @RequestBody Vegetation vegetation, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new ParamException(ResultEnum.PARAM_ERROR.getCode(),
                    result.getFieldError().getDefaultMessage());
        }
        vegetation.setId(storedVegetation.getId());

        vegetation.getDistribution().forEach(it -> it.setVegetation(vegetation));
        vegetation.getImages().forEach(it -> it.setVegetation(vegetation));
        vegetation.getListQuadrat().forEach(list -> {
            list.setVegetation(vegetation);
            list.getItems().forEach(item -> item.setListQuadrat(list));
        });
        String name =getVegetationService().findOne(storedVegetation.getId()).getName();
        Vegetation newVegetation = getVegetationService().save(vegetation);

        Class<?> clazz = VegetationsItemJsonController.class;
        Method method = clazz.getMethod("update", ReflectUtil.getPeremeterClass(clazz, "update"));
        ReflectUtil.setAnnotationOn(method,"更新植被库，名称："+name);

        return ResponseEntity.ok(getVegetationService().save(newVegetation));
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param vegetation
     * @return ResponseEntity
     */
    @DeleteMapping(name = "delete")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "path", dataType = "int", required = true)
    })
    @PreAuthorize("hasRole('DB_VEGETATION')")
    @ApiOperation(value = "",notes = "delete")
    public ResponseEntity<?> delete(@ApiIgnore @ModelAttribute Vegetation vegetation) throws Exception {
        getVegetationService().delete(vegetation);
        Class<?> clazz = VegetationsItemJsonController.class;
        Method method = clazz.getMethod("delete", ReflectUtil.getPeremeterClass(clazz, "delete"));
        ReflectUtil.setAnnotationOn(method,"删除植被库，名称："+vegetation.getName());
        return ResponseEntity.ok().build();
    }
}
